<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class Permission extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'permission';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成权限并绑定菜单';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $rows = DB::table('admin_menu')
            ->get();

        $date = date('Y-m-d H:i:s');
        $i = 0;
        foreach ($rows as $key => $row){

            $id = DB::table('admin_permissions')
                ->insertGetId([
                    'name' => $row->title,
                    'slug' => $this->geSlug(),
                    'http_path' => $row->uri ? '/'.$row->uri.'*' : '',
                    'order' =>  $row->order,
                    'parent_id' => $row->parent_id,
                    'created_at' => $date,
                ]);
            DB::table('admin_permission_menu')
                ->insert([
                    'permission_id' => $id,
                    'menu_id' => $row->id,
                    'created_at' => $date,
                    'updated_at' => $date,
                ]);
            $i++;
        }

        $this->info('总插入数据'.$i.'条');



        return Command::SUCCESS;
    }


    public function geSlug()
    {
        $slug = Str::random(6);

        $exists = DB::table('admin_permissions')
            ->where('slug',$slug)
            ->exists();

        if ($exists){
            $this->geSlug();
        }

        return $slug;
    }
}
